package org.openea.eap.module.obpm.util.form;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.openbpm.bus.api.model.IBusinessColumn;
import org.openbpm.bus.api.model.IBusinessTable;
import org.openea.eap.module.obpm.util.form.tableexcel.BusinessColumnExcellor;
import org.openea.eap.module.obpm.util.form.tableexcel.BusinessColumnExcellorFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;











public class BusinessTableExcellor
{
  private static Logger log = LoggerFactory.getLogger(BusinessTableExcellor.class);

  private IBusinessTable table;


  public BusinessTableExcellor(IBusinessTable table) { this.table = table; }










  public List<Map<String, Object>> fromExcel(List<Map<String, Object>> dataList) {
    log.debug("开始根据业务表【{}】解析excel内容：", this.table.getComment());
    log.debug("解析前：\n" + dataList.toString());
    List<Map<String, Object>> list = new ArrayList<>();
    dataList.forEach(data -> {
          Map<String, Object> map = new HashMap<>();
          //data.forEach(());
          for(String key: data.keySet()){
              map.put(key, data.get(key));
          }
          list.add(map);
        });
    log.debug("解析后：\n" + list);
    return list;
  }









  public List<Map<String, Object>> toExcel(JSONArray dataList) {
    log.debug("开始根据业务表【{}】转化excel内容：", this.table.getComment());
    log.debug("转化前：\n" + dataList.toString());
    List<Map<String, Object>> list = new ArrayList<>();
    for (int i = 0; i < dataList.size(); i++) {
      JSONObject data = dataList.getJSONObject(i);
      Map<String, Object> map = new HashMap<>();
      data.forEach((key, val) -> {
            IBusinessColumn column = this.table.getColumnByKey(key);
            BusinessColumnExcellor excellor = BusinessColumnExcellorFactory.get(column);
            Object value = val;
            if (excellor != null) {
              value = excellor.toExcel(column, val);
            }
            map.put(column.getKey(), value);
          });
      list.add(map);
    }
    log.debug("转化后：\n" + list);
    return list;
  }









  private IBusinessColumn getColumnByComment(String comment) {
    for (IBusinessColumn c : this.table.getColumns()) {
      if (comment.equals(c.getComment())) {
        return c;
      }
    }
    return null;
  }
}
